package shipment

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/types/order"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateOrderShipmentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateOrderShipmentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateOrderShipmentLogic {
	return &BackendCreateOrderShipmentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateOrderShipmentLogic) BackendCreateOrderShipment(in *order.OrderShipmentInfo) (*order.BaseResp, error) {
	if in.OrderSn == nil || len(strings.TrimSpace(*in.OrderSn)) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.No == nil || len(strings.TrimSpace(*in.No)) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Name == nil || len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Code == nil || len(strings.TrimSpace(*in.Code)) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.OrderType == nil || *in.OrderType == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, err
	}

	now := time.Now()
	if *in.OrderType == globalkey.NormalOrderShipment {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.OrderColumns.OrderSN] = map[string][]any{
			"equalTo": {strings.TrimSpace(*in.OrderSn)},
		}
		list, _, err := l.svcCtx.Order.GetList(l.ctx, model.M{
			"pageSize": uint64(1),
		}, -1, filterMap)
		if err != nil {
			return nil, err
		}

		if len(list) == 0 {
			return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
		}

		trade := list[0]
		if uint32(trade.TradeState) != globalkey.OrderTradeStatePaid && uint32(trade.TradeState) != globalkey.OrderTradeStateShipping {
			return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
		}

		no := strings.TrimSpace(*in.No)
		name := strings.TrimSpace(*in.Name)
		code := strings.TrimSpace(*in.Code)
		shipmentFilterMap := make(map[string]map[string][]any)
		shipmentFilterMap[model.OrderShipmentColumns.OrderID] = map[string][]any{
			"equalTo": {trade.ID},
		}
		shipmentFilterMap[model.OrderShipmentColumns.No] = map[string][]any{
			"equalTo": {no},
		}
		shipmentFilterMap[model.OrderShipmentColumns.OrderType] = map[string][]any{
			"equalTo": {*in.OrderType},
		}
		shipmentList, _, err := l.svcCtx.Order.GetShipmentList(l.ctx, model.M{
			"pageSize": uint64(1),
		}, -1, shipmentFilterMap)
		if err != nil {
			return nil, err
		}

		var result null.JSON
		if in.Result != nil && len(strings.TrimSpace(*in.Result)) > 0 {
			result = null.NewJSON([]byte(strings.TrimSpace(*in.Result)), true)
		}

		if len(shipmentList) > 0 {
			shipment := shipmentList[0]
			shipment.OrderType = uint8(*in.OrderType)
			shipment.Name = name
			shipment.Code = code
			shipment.Status = uint8(globalkey.StatusEnabled)

			shipment.Result = result
			shipment.UpdatedAt = now
			err = l.svcCtx.Order.UpdateShipment(l.ctx, tx, shipment)
			if err != nil {
				logx.Errorw("BackendCreateOrderShipment UpdateShipment Error:", logx.Field("detail", err.Error()))
				tx.Rollback()
				return nil, err
			}
		} else {
			err = l.svcCtx.Order.InsertShipment(l.ctx, tx, &model.OrderShipment{
				OrderID:   trade.ID,
				No:        no,
				OrderType: uint8(*in.OrderType),
				Name:      name,
				Code:      code,
				Status:    uint8(globalkey.StatusEnabled),
				Result:    result,
				UpdatedAt: now,
			})
			if err != nil {
				logx.Errorw("BackendCreateOrderShipment InsertShipment Error:", logx.Field("detail", err.Error()))
				tx.Rollback()
				return nil, err
			}
		}

		trade.TradeState = uint16(globalkey.OrderTradeStateShipped)
		err = l.svcCtx.Order.Update(l.ctx, tx, trade, nil)
		if err != nil {
			logx.Errorw("BackendCreateOrderShipment Order Update Error:", logx.Field("detail", err.Error()))
			tx.Rollback()
			return nil, err
		}
	} else if *in.OrderType == globalkey.AfterSaleOrderShipment {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AfterSaleRequestColumns.AfterSalesSN] = map[string][]any{
			"equalTo": {strings.TrimSpace(*in.OrderSn)},
		}
		list, _, err := l.svcCtx.AfterSaleRequest.GetList(l.ctx, model.M{
			"pageSize": uint64(1),
		}, -1, filterMap)
		if err != nil {
			return nil, err
		}

		if len(list) == 0 {
			return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
		}

		afterSale := list[0]
		if uint32(afterSale.Status) != globalkey.AfterSaleStatusAwaitBarter {
			return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
		}

		no := strings.TrimSpace(*in.No)
		name := strings.TrimSpace(*in.Name)
		code := strings.TrimSpace(*in.Code)
		shipmentFilterMap := make(map[string]map[string][]any)
		shipmentFilterMap[model.OrderShipmentColumns.OrderID] = map[string][]any{
			"equalTo": {afterSale.ID},
		}
		shipmentFilterMap[model.OrderShipmentColumns.No] = map[string][]any{
			"equalTo": {no},
		}
		shipmentFilterMap[model.OrderShipmentColumns.OrderType] = map[string][]any{
			"equalTo": {*in.OrderType},
		}
		shipmentList, _, err := l.svcCtx.Order.GetShipmentList(l.ctx, model.M{
			"pageSize": uint64(1),
		}, -1, shipmentFilterMap)
		if err != nil {
			return nil, err
		}

		var result null.JSON
		if in.Result != nil && len(strings.TrimSpace(*in.Result)) > 0 {
			result = null.NewJSON([]byte(strings.TrimSpace(*in.Result)), true)
		}

		if len(shipmentList) > 0 {
			shipment := shipmentList[0]
			shipment.OrderType = uint8(*in.OrderType)
			shipment.Name = name
			shipment.Code = code
			shipment.Status = uint8(globalkey.StatusEnabled)
			shipment.Result = result
			shipment.UpdatedAt = now
			err = l.svcCtx.Order.UpdateShipment(l.ctx, tx, shipment)
			if err != nil {
				logx.Errorw("BackendCreateOrderShipment UpdateShipment Error:", logx.Field("detail", err.Error()))
				tx.Rollback()
				return nil, err
			}
		} else {
			err = l.svcCtx.Order.InsertShipment(l.ctx, tx, &model.OrderShipment{
				OrderID:   afterSale.ID,
				No:        no,
				OrderType: uint8(*in.OrderType),
				Name:      name,
				Code:      code,
				Status:    uint8(globalkey.StatusEnabled),
				Result:    result,
				UpdatedAt: now,
			})
			if err != nil {
				logx.Errorw("BackendCreateOrderShipment InsertShipment Error:", logx.Field("detail", err.Error()))
				tx.Rollback()
				return nil, err
			}
		}

		afterSale.Status = uint8(globalkey.AfterSaleStatusShipped)
		err = l.svcCtx.AfterSaleRequest.Update(l.ctx, tx, afterSale)
		if err != nil {
			logx.Errorw("BackendCreateOrderShipment AfterSaleRequest Update Error:", logx.Field("detail", err.Error()))
			tx.Rollback()
			return nil, err
		}
	}

	tx.Commit()

	return &order.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
